﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace Job.Controllers
{
    public class AnalysisController : Controller
    {
        JobDataContext db = new JobDataContext();
        // GET: Analysis
        public ActionResult Index()
        {
            JobSumFunction();                   //1
            EducationBackgroundSumFunction(); //2
            InitSalaryFunction();             //3
            SalaryAvgFunction();              //4
            CompanyTypeSumFunction();           //6
            IndustrySumFunction();              //5
            return View();
        }

        /// <summary>
        /// 求工资的最高、最低平均数
        /// </summary>
        public void SalaryAvg()
        {
            var ruselt = from r in db.positions
                         where r.searchKeyWord == "php"
                         where r.Salary != ""
                         select r;
            double startNum = 0.0;
            double endNum = 0.0;
            int error = 0;
            foreach (var item in ruselt)
            {
                MatchCollection mc = Regex.Matches(item.Salary, @"\d{1,2}\.\d{1,2}|\d{1,3}");
                if (Regex.Match(item.Salary, @"(\d{1,}|\d{1}.\d{1,2})-(\d{1,}|\d{1}.\d{1,2})万/月").Success)
                {
                    startNum += Convert.ToDouble(mc[0].Value) * 10.0;
                    endNum += Convert.ToDouble(mc[1].Value) * 10.0;
                }
                else if (Regex.Match(item.Salary, @"(\d{1,}|\d{1}.\d{1,2})-(\d{1,}|\d{1}.\d{1,2})万/年").Success)   // 匹配模式：__-__万/年
                {
                    startNum += Convert.ToDouble(mc[0].Value) * 10.0 / 12;
                    endNum += Convert.ToDouble(mc[1].Value) * 10.0 / 12;
                }
                else if (Regex.Match(item.Salary, @"(\d{1,}|\d{1}.\d{1,2})-(\d{1,}|\d{1}.\d{1,2})千/月").Success)     // 匹配模式：__-__千/月
                {
                    startNum += Convert.ToDouble(mc[0].Value);
                    endNum += Convert.ToDouble(mc[1].Value);
                }
                else
                {
                    error++;
                }
            }
            double startAvg = startNum / ruselt.Count();
            double endAvg = endNum / ruselt.Count();
            ViewBag.startAvg = startAvg;
            ViewBag.endAvg = endAvg;
        }
        
        /// <summary>
        /// 1、统计三类职位的数据数量，对采集的数据进行说明。
        /// </summary>
        public void JobSumFunction()
        {
            var keyWordName = (from a in db.positions
                               group a by a.searchKeyWord into typeName
                               select typeName.Count()).ToList();
            ViewBag.phpSum = keyWordName[0];
            ViewBag.javaSum = keyWordName[1];
            ViewBag.netSum = keyWordName[2];
        }

        /// <summary>
        /// 2、按各类职位，对所有企业进行学历要求的统计，分析各个职位的学历分布情况。
        /// </summary>
        public void EducationBackgroundSumFunction()
        {
            var JobDatas = from j in db.positions group j by j.searchKeyWord into e select e;
            int[,] allArr = new int[3, 6];
            int i = 0;
            string[] eb = { "无需学历", "中专", "高中", "大专", "本科", "硕士" };
            foreach (var JobData in JobDatas)
            {
                var jobs = from job in JobData
                           group job by job.EducationBackground into g
                           select new
                           {
                               g.Key,
                               number = g.Count()
                           };
                for(int j=0;j<eb.Length;j++)
                {
                    allArr[i,j] = jobs.Where(t => t.Key == eb[j]).Select(t=>t.number).First();
                }
                i++;
            }
            ViewBag.phpEducationBackground = allArr[0,0] + "," + allArr[0, 1] + "," + allArr[0, 2] + "," + allArr[0, 3] + "," + allArr[0, 4] +","+ allArr[0,5];
            ViewBag.javaEducationBackground = allArr[1, 0] + "," + allArr[1, 1] + "," + allArr[1, 2] + "," + allArr[1, 3] + "," + allArr[1, 4] +","+ allArr[1,5];
            ViewBag.netEducationBackground = allArr[2, 0] + "," + allArr[2, 1] + "," + allArr[2, 2] + "," + allArr[2, 3] + "," + allArr[2, 4] +","+ allArr[2,5];
        }

        /// <summary>
        /// 3、统计三类职位的起薪，分析分布规律。
        /// </summary>
        public void InitSalaryFunction()
        {
            var result = from p in db.positions
                         group p by p.searchKeyWord into GroupPositions
                         select GroupPositions;
            int[,] allSalary = new int[3, 5];
            int i = 0;
            foreach (var item in result)
            {
                int[] salaryArr = ClassSalary(item);
                for (int j = 0; j < salaryArr.Length; j++)
                {
                    allSalary[i, j] = salaryArr[j];
                }
                i++;
            }
            ViewBag.phpInitSalary = allSalary[0, 0] + "," + allSalary[0, 1] + "," + allSalary[0, 2] + "," + allSalary[0, 3] + "," + allSalary[0, 4];
            ViewBag.javaInitSalary = allSalary[1, 0] + "," + allSalary[1, 1] + "," + allSalary[1, 2] + "," + allSalary[1, 3] + "," + allSalary[1, 4];
            ViewBag.netInitSalary = allSalary[2, 0] + "," + allSalary[2, 1] + "," + allSalary[2, 2] + "," + allSalary[2, 3] + "," + allSalary[2, 4];
        }

        public int[] ClassSalary(IGrouping<string, positions> positions)
        {
            int[] salaryArr = { 0, 0, 0, 0, 0 };    // int数组，第一个是5k以下，第二个是5k-10k，第三个10k-15k，第四个15k-20k，第五个20k以上
            int errorItem = 0;
            foreach (var item in positions)
            {
                MatchCollection mc = Regex.Matches(item.Salary, @"\d{1,2}\.\d{1,2}|\d{1,3}");   // 根据匹配模式，获取匹配的工资字符串
                if (Regex.Match(item.Salary, @"(\d{1,}|\d{1}.\d{1,2})-(\d{1,}|\d{1}.\d{1,2})万/月").Success)   // 匹配模式：__-__万/月
                {
                    string t = (Convert.ToDouble(mc[0].Value) * 10.0).ToString();   // double类型需要先转成string类型
                    salaryArr[JudgeSite(int.Parse(t))]++;
                }
                else if (Regex.Match(item.Salary, @"(\d{1,}|\d{1}.\d{1,2})-(\d{1,}|\d{1}.\d{1,2})万/年").Success)   // 匹配模式：__-__万/年
                {
                    salaryArr[JudgeSite(Convert.ToInt32(mc[0].Value) * 10 / 12)]++;
                }
                else if (Regex.Match(item.Salary, @"(\d{1,}|\d{1}.\d{1,2})-(\d{1,}|\d{1}.\d{1,2})千/月").Success)     // 匹配模式：__-__千/月
                {
                    salaryArr[JudgeSite(Convert.ToInt32(Math.Ceiling(Convert.ToDouble(mc[0].Value))))]++;
                }
                else
                {
                    errorItem++;
                }
            }
            return salaryArr;
        }

        /// <summary>
        /// 判断工资属于哪个位置
        /// </summary>
        /// <param name="salary">工资</param>
        /// <returns></returns>
        public int JudgeSite(int salary)
        {
            if (salary < 5)
                return 0;
            else if (salary < 10)
                return 1;
            else if (salary < 15)
                return 2;
            else if (salary < 20)
                return 3;
            else
                return 4;
        }

        /// <summary>
        /// 4、计算三类职位的平均工资，分析哪个平均工资更高。
        /// </summary>
        public void SalaryAvgFunction()
        {
            var results = from p in db.positions
                          group p by p.searchKeyWord into g
                          select g;
            double[] allArr = new double[3];
            int i = 0;
            foreach (var group in results)
            {
                double avg = 0;
                foreach (var position in group)
                {
                    MatchCollection mc = Regex.Matches(position.Salary, @"\d{1,2}\.\d{1,2}|\d{1,3}");
                    if (Regex.Match(position.Salary, @"(\d{1,}|\d{1}.\d{1,2})-(\d{1,}|\d{1}.\d{1,2})万/月").Success)
                    {
                        avg += (Convert.ToDouble(mc[0].Value) + Convert.ToDouble(mc[1].Value))/2 * 10.0;
                    }
                    else if (Regex.Match(position.Salary, @"(\d{1,}|\d{1}.\d{1,2})-(\d{1,}|\d{1}.\d{1,2})万/年").Success)   // 匹配模式：__-__万/年
                    {
                        avg += (Convert.ToDouble(mc[0].Value) + Convert.ToDouble(mc[1].Value))/ 2 * 10.0 / 12;
                    }
                    else if (Regex.Match(position.Salary, @"(\d{1,}|\d{1}.\d{1,2})-(\d{1,}|\d{1}.\d{1,2})千/月").Success)     // 匹配模式：__-__千/月
                    {
                        avg += (Convert.ToDouble(mc[0].Value) + Convert.ToDouble(mc[1].Value)) / 2;
                    }
                }
                allArr[i] = avg / group.Count();
                i++;
            }
            ViewBag.avgSalary = allArr[0] + "," + allArr[1] + "," + allArr[2];
        }

        /// <summary>
        /// 按公司的工作地点，统计各类职位的企业数量，分析哪些地方就业更容易。
        /// </summary>
        public void AreaSumFunction()
        {
            var results = from p in db.positions
                          group p by p.searchKeyWord into g
                          select g;
            List<string> areaList = new List<string>();
            foreach(var item in results)
            {
                foreach(var position in item)
                {
                    if(position.Area.Length > 4)
                    {
                        string[] area = position.Area.Split('-');
                        areaList.Add(area[0]);
                    }
                    else
                    {
                        areaList.Add(position.Area);
                    }
                }
                areaList = areaList.Distinct().ToList();
            }
        }

        /// <summary>
        /// 6、统计各类职位的企业上市情况。
        /// </summary>
        public void CompanyTypeSumFunction()
        {
            var results = from p in db.positions
                          group p by p.searchKeyWord into g
                          select g;
            int[,] typeArr = new int[3, 10];
            string[] ct = { "合资", "民营公司", "国企", "外资（欧美）", "外资（非欧美）", "非营利组织", "上市公司", "创业公司", "事业单位", "外企代表处" };
            int i = 0;
            foreach(var item in results)
            {
                var positionList = from o in item
                                   group o by o.CompanyType into g
                                   select new
                                   {
                                       g.Key,
                                       Value = g.Count()
                                   };
                
                for(int j = 0;j<ct.Length;j++)
                {
                    typeArr[i, j] = positionList.Where(t => t.Key == ct[j]).Select(t => t.Value).FirstOrDefault();
                }
                i++;
            }
            ViewBag.phpCompanyType = typeArr[0, 0] + "," + typeArr[0, 1] + "," + typeArr[0, 2] + "," + typeArr[0, 3] + "," + typeArr[0, 4] + "," + typeArr[0, 5] + "," + typeArr[0, 6] + "," + typeArr[0, 7] + "," + typeArr[0, 8] + "," + typeArr[0, 9];
            ViewBag.javaCompanyType = typeArr[1, 0] + "," + typeArr[1, 1] + "," + typeArr[1, 2] + "," + typeArr[1, 3] + "," + typeArr[1, 4] + "," + typeArr[1, 5] + "," + typeArr[1, 6] + "," + typeArr[1, 7] + "," + typeArr[1, 8] + "," + typeArr[1, 9];
            ViewBag.netCompanyType = typeArr[2, 0] + "," + typeArr[2, 1] + "," + typeArr[2, 2] + "," + typeArr[2, 3] + "," + typeArr[2, 4] + "," + typeArr[2, 5] + "," + typeArr[2, 6] + "," + typeArr[2, 7] + "," + typeArr[2, 8] + "," + typeArr[2, 9];
        }

        /// <summary>
        /// 5、统计各类职位中行业的分布情况。
        /// </summary>
        public void IndustrySumFunction()
        {
            var t1 = from p in db.positions
                          where System.Data.Linq.SqlClient.SqlMethods.Like(p.Industry, "%" + " " + "%")
                          group p by p.searchKeyWord into g
                         select g;
            List<IndustrySum> industrySums = new List<IndustrySum>();
            int i = 0;
            foreach(var positionsGroup in t1)
            {
                foreach(var position in positionsGroup)
                {
                    string parmartTxt = position.Industry.Trim();
                    int startIndex = parmartTxt.IndexOf(" ");
                    int endIndex = parmartTxt.LastIndexOf(" ");
                    string code1 = parmartTxt.Substring(0, startIndex-1);
                    string code2 = parmartTxt.Remove(0, endIndex+1);
                    switch (i)
                    {
                        case 0:
                            if(industrySums.Where(t=>t.Name == code1).Count() > 0)
                            {
                                industrySums.Where(t => t.Name == code1).First().PhpNum++;
                            }
                            else
                            {
                                IndustrySum industry = new IndustrySum()
                                {
                                    Name = code1,
                                    PhpNum = 1
                                };
                                industrySums.Add(industry);
                            }
                            if (industrySums.Where(t => t.Name == code2).Count() > 0)
                            {
                                industrySums.Where(t => t.Name == code2).First().PhpNum++;
                            }
                            else
                            {
                                IndustrySum industry = new IndustrySum()
                                {
                                    Name = code2,
                                    PhpNum = 1
                                };
                                industrySums.Add(industry);
                            }
                            break;
                        case 1:
                            if (industrySums.Where(t => t.Name == code1).Count() > 0)
                            {
                                industrySums.Where(t => t.Name == code1).First().JavaNum++;
                            }
                            else
                            {
                                IndustrySum industry = new IndustrySum()
                                {
                                    Name = code1,
                                    JavaNum = 1
                                };
                                industrySums.Add(industry);
                            }
                            if (industrySums.Where(t => t.Name == code2).Count() > 0)
                            {
                                industrySums.Where(t => t.Name == code2).First().JavaNum++;
                            }
                            else
                            {
                                IndustrySum industry = new IndustrySum()
                                {
                                    Name = code2,
                                    JavaNum = 1
                                };
                                industrySums.Add(industry);
                            }
                            break;
                        case 2:
                            if (industrySums.Where(t => t.Name == code1).Count() > 0)
                            {
                                industrySums.Where(t => t.Name == code1).First().NetNum++;
                            }
                            else
                            {
                                IndustrySum industry = new IndustrySum()
                                {
                                    Name = code1,
                                    NetNum = 1
                                };
                                industrySums.Add(industry);
                            }
                            if (industrySums.Where(t => t.Name == code2).Count() > 0)
                            {
                                industrySums.Where(t => t.Name == code2).First().NetNum++;
                            }
                            else
                            {
                                IndustrySum industry = new IndustrySum()
                                {
                                    Name = code2,
                                    NetNum = 1
                                };
                                industrySums.Add(industry);
                            }
                            break;
                    }
                }
                i++;
            }
            var t2 = from p in db.positions
                     where !(from po in db.positions
                             where System.Data.Linq.SqlClient.SqlMethods.Like(po.Industry, "%" + " " + "%")
                             select po.id).Contains(p.id)
                     group p by p.searchKeyWord into g
                     select g;
            i = 0;
            foreach (var positions in t2)
            {
                foreach(var item in positions)
                {
                    switch (i)
                    {
                        case 0:
                            if (industrySums.Where(t => t.Name == item.Industry).Count() > 0)
                            {
                                industrySums.Where(t => t.Name == item.Industry).First().PhpNum++;
                            }
                            else
                            {
                                IndustrySum industry = new IndustrySum()
                                {
                                    Name = item.Industry,
                                    PhpNum = 1
                                };
                                industrySums.Add(industry);
                            }
                            break;
                        case 1:
                            if (industrySums.Where(t => t.Name == item.Industry).Count() > 0)
                            {
                                industrySums.Where(t => t.Name == item.Industry).First().JavaNum++;
                            }
                            else
                            {
                                IndustrySum industry = new IndustrySum()
                                {
                                    Name = item.Industry,
                                    JavaNum = 1
                                };
                                industrySums.Add(industry);
                            }
                            break;
                        case 2:
                            if (industrySums.Where(t => t.Name == item.Industry).Count() > 0)
                            {
                                industrySums.Where(t => t.Name == item.Industry).First().NetNum++;
                            }
                            else
                            {
                                IndustrySum industry = new IndustrySum()
                                {
                                    Name = item.Industry,
                                    NetNum = 1
                                };
                                industrySums.Add(industry);
                            }
                            break;
                    }
                }
                i++;
            }
            var dics = from entry in industrySums orderby (entry.PhpNum +entry.JavaNum+entry.NetNum) ascending select entry;
            string industryStrKey = "";
            string phpIndustryStrValue = "";
            string javaIndustryStrValue = "";
            string netIndustryStrValue = "";
            foreach (var item in dics)
            {
                industryStrKey += item.Name + ",";
                phpIndustryStrValue += item.PhpNum + ",";
                javaIndustryStrValue += item.JavaNum + ",";
                netIndustryStrValue += item.NetNum + ",";
            }
            ViewBag.industryStrKey = industryStrKey.Substring(0, industryStrKey.Length-1);
            ViewBag.phpIndustryStrValue = phpIndustryStrValue.Substring(0, phpIndustryStrValue.Length - 1);
            ViewBag.javaIndustryStrValue = javaIndustryStrValue.Substring(0, javaIndustryStrValue.Length - 1);
            ViewBag.netIndustryStrValue = netIndustryStrValue.Substring(0, netIndustryStrValue.Length - 1);
        }
    }
    public class IndustrySum
    {
        public string Name { get; set; }
        public int PhpNum { get; set; }
        public int JavaNum { get; set; }
        public int NetNum { get; set; }
    }
}